package com.xiaogao.serviceMsm.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.xiaogao.commonUtils.Result;
import com.xiaogao.commonUtils.utils.RandomUtil;
import com.xiaogao.serviceMsm.service.MsmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 小高
 * @createtime 2021-06-29-15:27
 * @description
 */
@RestController
@RequestMapping("/api/msm")
@Api(description = "短信验证码")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送短信")
    @GetMapping("/send/{phone}")
    public Result code(@PathVariable("phone") String phone){
        // 从redis中获取验证码，如果获取到则返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        // 获取不到，向腾讯云发送
        // 生成随机验证码
        code = RandomUtil.getFourBitRandom();
        // 调用service发送短信的方法
        boolean isSend = msmService.send(code,phone);
        if (isSend){
            // 发送成功,把发送成功验证码放到redis里面并设置有效时间
            redisTemplate.opsForValue().setIfAbsent(phone,code,1, TimeUnit.MINUTES);
            return Result.ok();
        }else{
            return Result.error().message("短信发送失败");
        }
    }
}
